extends ColorRect

class_name JamProgressBar

onready var TOP_PANEL = find_parent("top_panel")

var intersect_color = Color8(10,10,10,255)
var intersect_width = 2

var progress = 0.0
var progress_rate = 0.2

var active = false

var ping_rect
var time_bonus = 0.040 # per second of jam time

var reward = 0

var reward_sections = [
	0,
	0.5,
	0.8,
	1
]

var reward_base_amounts = [
	0.0,
	0.3,
	0.6,
]

var actual_amounts = []

var rates = [
	2.0,
	1.3,
	0.4,
]

var reward_colors = [
	Color8(50,50,50,255),
	Color8(250,250,0,255),
	Color8(250,150,0,255),
]

var jam_progress_bar_color = ColorN("white")
var progress_bar
var reward_labels = []

var ping_label

# Called when the node enters the scene tree for the first time.
func _ready():
	color = ColorN("black")
	
	progress_bar = ColorRect.new()
	progress_bar.color = jam_progress_bar_color
	progress_bar.rect_size.y = rect_size.y
	call_deferred("add_child",progress_bar)
	
	for i in range(reward_colors.size()):
		var r = ColorRect.new()
		r.color = reward_colors[i]
		var p = reward_sections[i] * rect_size.x
		r.rect_position.x = p
		var size = Vector2(reward_sections[i+1] * rect_size.x - p, rect_size.y)
		r.rect_size = size
		var shadermat = ShaderMaterial.new()
		shadermat.shader = load("res://multiplier.shader")
		r.material = shadermat
		call_deferred("add_child",r)
		
		var ping_label = FontedLabel.new()
		ping_label.rect_position.x = p
		ping_label.rect_size = size
		ping_label.font_size = rect_size.y * 0.5
		ping_label.align = Label.ALIGN_CENTER
		ping_label.valign = Label.ALIGN_CENTER
		ping_label.text = "ping"
		call_deferred("add_child",ping_label)
		reward_labels.append(ping_label)
		
		

func activate():
	reward = 0
	actual_amounts.clear()
	active = true
	var planet = TOP_PANEL.planet
	for r in reward_base_amounts:
		var reward_with_time =  r * (1 + TOP_PANEL.time_left_bar.max_time_left*time_bonus)
		var adjusted_per_type = reward_with_time * planet.jam_rewards[planet.jam]
		actual_amounts.append( adjusted_per_type)
	update_labels()
	pass
func deactivate():
	active = false
	find_parent("SHIP").fuel = clamp(find_parent("SHIP").fuel +reward,0.0,1.0)
	reward = 0

func update_labels():
	for l in range(len(reward_labels)):
		reward_labels[l].text = "+"+str(floor(actual_amounts[l] *100)/100.0)

func _process(delta):
	if active:
		if ping_rect == null:
			ping_rect = TOP_PANEL.ping_rect
		
		progress_rate = rates[ping_rect.ring_index] / TOP_PANEL.time_left_bar.max_time_left
		progress_bar.rect_size.x = progress * rect_size.x
		progress += progress_rate * delta
		for i in range(len(actual_amounts)):
			if progress >= reward_sections[i]:
				print(reward)
				reward = max(reward,actual_amounts[i])
